An Introduction to the Package Plotly

What is Plotly?

Plotly is a graphing library that allows you to make publication-quality graphs. It not only can be used along with R, but python, and matlab as well as other software. Not only can you make beautiful publication quality plots, maps, charts etc. but they are interactive as well, allowing you to view individual datapoints within a plot.

loading

Install the package

First you can install the package, and then I will walk you through a few of the basic but useful functions within the plotly package.

#install.packages("plotly")

image

Load the package and data

library(plotly)
library(tidyverse)
library(rmdformats)

DuBois<-tibble::tribble(
  ~Year, ~Property.Valuation,
  1870L,             300000L,
  1871L,             800000L,
  1872L,            1100000L,
  1873L,            1200000L,
  1874L,            1150000L,
  1875L,            1200000L,
  1876L,            1180000L,
  1877L,            1100000L,
  1878L,            1050000L,
  1879L,            1050000L,
  1880L,            1200000L,
  1881L,            1400000L,
  1882L,            1600000L,
  1883L,            1800000L,
  1884L,            1900000L,
  1885L,            2000000L,
  1886L,            2200000L,
  1887L,            2500000L,
  1888L,            2700000L,
  1889L,            3200000L,
  1890L,            3400000L,
  1891L,            4000000L,
  1892L,            4700000L,
  1893L,            4850000L,
  1894L,            4600000L,
  1895L,            4300000L,
  1896L,            4300000L,
  1897L,            4200000L,
  1898L,            4300000L,
  1899L,            4300000L,
  1900L,            4350000L
  )

Example 1: Learning how to make an interactive Plot

Lets say we want to make a simple scatterplot or line graph: Unlike we are used to, we will not be starting our code with ggplot! Shocking I know!

#plot_ly(Dubois, x= ~Year,
#y = ~ property.valuation,

#type= ‘scatter’,

#mode= ‘lines+markers’)%>%

# How to add a title to your plot

#layout(title = list(text= ‘Whatever you want the plot title to be’))

Rather than using geom()…

#type= ‘scatter’,

#mode= ‘lines+markers’)%>%

# How to add a title to your plot

#layout(title = list(text= ‘Whatever you want the plot title to be’))
####learn how to save plots and if its the same or if you can use the here package

Now let’s run it all together:

plot_ly(DuBois, x= ~Year, y = ~Property.Valuation, type = 'scatter', mode = 'lines+markers') %>% 
  layout(title= list(text= 'This is my rendition of DuBois graph'))

Example 2: Making a bubble chart with continuous data

example <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv")
fig <- plot_ly(example, x = ~Women, 
               y = ~Men, 
               text = ~School, 
               type = 'scatter', 
               mode = 'markers', 
               color = ~Gap, colors = 'Reds',
        marker = list(size = ~Gap, opacity = 0.5))

fig <- fig %>% layout(title = 'Gender Gap in Earnings per University',
         xaxis = list(showgrid = FALSE),
         yaxis = list(showgrid = FALSE))
fig

Let’s move on to something a little more… complex

Now that you have learned a bit about how interactive figures are able to get with this package, lets take it a step further and learn how to incorporate even more interactive customizations.

complex

Histograms:

Basic Histogram

Making the most basic histograms only requires one line of code!

his1 <- plot_ly(x = ~rnorm(50), type = "histogram")

his1

Normalized Histogram

Now, let’s make a normalized histogram, with one more added argument.

his2 <- plot_ly(x = ~rnorm(50),
             type = "histogram",
             histnorm = "probability")

his2

Making Interactive Maps

Now that we know the basics of plotly, as well as how to make a few different types of graphs, let’s explore some more advanced figures by creating interactive maps.

The maps you can create using Plotly are called Choropleth maps, which are made up of separate polygons, which can each be a different color

US States by Population

First, let’s read in the data set.

statepop <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/2014_usa_states.csv")

Next, we need to create the hovering part of the map. This will allow the user to scroll over each state to get the population info.

The
helps to separate each piece into a different line on the visual.

statepop$hover <- with(statepop, paste(State, '<br>',Postal, '<br>'))

Now, it’s time to start building the actual map using plot_geo.

statepop$hover <- with(statepop, paste(State, '<br>',Postal, '<br>'))

map1 <- plot_geo(statepop, locationmode = 'USA-states')
popup1 <- map1 %>% 
  add_trace(z = ~Population, 
            text = ~hover, 
            locations = ~Postal,
            color = ~Population, 
            colors = 'Purples'
  )

Finally, we add on a legend using ‘colorbar’ and add title.

statepop$hover <- with(statepop, paste(State, '<br>',Postal, '<br>'))

map1 <- plot_geo(statepop, locationmode = 'USA-states')
popup1 <- map1 %>% add_trace(
    z = ~Population, text = ~hover, locations = ~Postal,
    color = ~Population, colors = 'Purples'
  )
fig <- popup1 %>% colorbar(title = "Population")
usmap1 <- fig %>% layout(
    title = 'State populations in 2014'
  )

usmap1

Zoom in to only include the US

We can narrow down the map to only show the US in order to ge a closer view. In order to do this, we will have to make a list.

g <- list(
  scope = 'usa',
  projection = list(type = 'albers usa'),
  showlakes = TRUE,
  lakecolor = toRGB('white')
)

It will be inserted after statepop$hover.

statepop <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/2014_usa_states.csv")
statepop$hover <- with(statepop, paste(State, '<br>',Postal, '<br>'))

g <- list(
  scope = 'usa',
  projection = list(type = 'albers usa'),
  showlakes = TRUE,
  lakecolor = toRGB('white')
)

map1 <- plot_geo(statepop, locationmode = 'USA-states')
popup1 <- map1 %>% add_trace(
    z = ~Population, text = ~hover, locations = ~Postal,
    color = ~Population, colors = 'Purples'
  )
fig1 <- popup1 %>% colorbar(title = "Population")
usmap <- fig1 %>% layout(
    title = 'State populations in 2014)',
    geo = g
  )

usmap

Think Pair Share

Spend 5 minutes to make a interactive map with the agricultural exports data set below.

https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv

Results

Your code and map should look something like this

agexports <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv")
agexports$hover <- with(agexports, paste(state, '<br>', "Beef", beef, "Dairy", dairy, "<br>", "Fruits", total.fruits, "Veggies", total.veggies, "<br>", "Wheat", wheat, "Corn", corn))

g <- list(
  scope = 'usa',
  projection = list(type = 'albers usa'),
  showlakes = TRUE,
  lakecolor = toRGB('white')
)

map <- plot_geo(agexports, locationmode = 'USA-states')
popup <- map %>% add_trace(
    z = ~total.exports, text = ~hover, locations = ~code,
    color = ~total.exports, colors = 'Purples'
  )
fig1 <- popup %>% colorbar(title = "Millions USD")
fig2 <- fig1 %>% layout(
    title = 'US Agriculture Exports by State)',
    geo = g
  )

fig2

Using Buttons

Another cool option you can use with plotly is buttons and sliders. We won’t code any today for the sake of time, but if you wanted to insert interactive buttons on a plot, you would use the format shown below.

There are 3 main method types for creating buttons:

  • restyle: modify data or data attributes
  • relayout: modify layout attributes
  • update: modify data and layout attributes

Let’s take a look at Plotly’s page on buttons: here

Summary

Some of the Plotly features we learned today were:

  • plot_geo: for maps
  • plot_ly: for graphs
  • $hover: to create interactive information pop ups
  • making lists
  • intro to making buttons

Plotly is a great option for making:

  • line graphs
  • histograms
  • interactive maps

More options to explore with plotly:

  • scatter plots
  • box plots
  • heatmaps

Plotly’s page for R includes many helpful resources and examples for each type of figure.

Find it here!